package dibujar;
// Blob Finder Demo
// A.Greensted
// http://www.labbookpages.co.uk
// Please use however you like. I'd be happy to hear any feedback or comments.

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.HeadlessException;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.Toolkit;
import java.awt.Transparency;
import java.awt.geom.Ellipse2D;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.DataBuffer;
import java.awt.image.DataBufferByte;
import java.awt.image.PixelGrabber;
import java.awt.image.Raster;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

import dibujar.BlobFinder.Blob;

import ejemplo.utilidades;

public class BlobDemo
{	
	protected static Image entryImage;
	public static String sReconocido = "";
	private static Image loadedImage;
	  
	protected static Graphics entryGraphics;
	
	public static Image toImage(BufferedImage bufferedImage) {
	    return Toolkit.getDefaultToolkit().createImage(bufferedImage.getSource());
	}
	

	
	/*public static BufferedImage toBufferedImage(Image image) {
	
		if (image instanceof BufferedImage) {
			
			System.out.println("1");
			return ((BufferedImage) image);
		} else {
		
			image = new ImageIcon(image).getImage();
			System.out.println("2");
		
			BufferedImage bufferedImage = new BufferedImage(image
					.getWidth(null), image.getHeight(null),
					BufferedImage.TYPE_USHORT_GRAY);
			Graphics g = bufferedImage.createGraphics();
			g.drawImage(image, 0, 0, null);
			g.dispose();
			return (bufferedImage);
		}
	}*/
	
	 public static Image loadImage(String name) throws InterruptedException {

         JLabel label = new JLabel();
         MediaTracker media = new MediaTracker(label);
         
         //Image imagen = Toolkit.getDefaultToolkit().getImage ("/path_absoluto/fichero.gif");
         
         loadedImage = Toolkit.getDefaultToolkit().getImage (name);
         media.addImage(loadedImage, 23);
         
         try
         {
            media.waitForID(23);
         }
         catch (InterruptedException e)
         {
            System.out.println ("Me han interrumpido");
            System.out.println ("Puede que la imagen todavía no haya terminado de cargarse");
         }
                 
         // utilidades.salvarImagen(toBufferedImage(loadedImage), "/jj.png","png");
          
		return loadedImage;
	 }
	 
	
	/**
	 * @return
	 */
	public List<Blob> BlobDemo(  BufferedImage imagen)
	{
		BufferedImage srcImage = null;
		
		utilidades.salvarImagen(imagen,"/prueba.png","png");
		
		try
		{
			File imgFile = new File("/prueba.png");
			srcImage = javax.imageio.ImageIO.read(imgFile);
		}
		catch (IOException ioE)
		{
			System.err.println(ioE);
			System.exit(1);
		}

		
		int width = srcImage.getWidth();
		int height = srcImage.getHeight();

		// Get raw image data
		Raster raster = srcImage.getData();
		DataBuffer buffer = raster.getDataBuffer();

		int type = buffer.getDataType();
		if (type != DataBuffer.TYPE_BYTE)
		{
			System.err.println("Wrong image data type");
			System.exit(1);
		}
		if (buffer.getNumBanks() != 1)
		{
			System.err.println("Wrong image data format");
			System.exit(1);
		}

		DataBufferByte byteBuffer = (DataBufferByte) buffer;
		byte[] srcData = byteBuffer.getData(0);

		// Sanity check image
		if (width * height * 3 != srcData.length) {
			System.err.println("Unexpected image data size. Should be RGB image");
			System.exit(1);
		}
		
	
		// Create Monochrome version - using basic threshold technique
		byte[] monoData = new byte[width * height];
		int srcPtr = 0;
		int monoPtr = 0;

		while (srcPtr < srcData.length)
		{
			int val = ((srcData[srcPtr]&0xFF) + (srcData[srcPtr+1]&0xFF) + (srcData[srcPtr+2]&0xFF)) / 3;
			monoData[monoPtr] = (val > 128) ? (byte) 0xFF : 0;

			srcPtr += 3;
			monoPtr += 1;
		}

		byte[] dstData = new byte[srcData.length];

		// Create Blob Finder
		BlobFinder finder = new BlobFinder(width, height);

		ArrayList<BlobFinder.Blob> blobList = new ArrayList<BlobFinder.Blob>();
		finder.detectBlobs(monoData, dstData, 0, -1, (byte)0, blobList);
		

		// Create a graphics context on the buffered image
		Graphics2D g2d = srcImage.createGraphics();
		// Draw on the image
		g2d.setColor(Color.red);
		
		// List Blobs
		System.out.printf("Found %d blobs:\n", blobList.size());
		for (BlobFinder.Blob blob : blobList) {			
			g2d.drawRect(blob.xMin,blob.yMin,blob.xMax-blob.xMin,blob.yMax-blob.yMin);
		
		}
		
		

		
		g2d.dispose();
	/*	
		entryImage = createImage(10, 10);
		
		entryImage=toImage(srcImage);
		*/
		
		
		//utilidades.salvarImagen(srcImage,"/prueba.png","png");
		
	
		
		//return blobList;
		
		// Create GUI
	/*	RGBFrame srcFrame = new RGBFrame(width, height, srcData);
		RGBFrame dstFrame = new RGBFrame(width, height, dstData);
		
	
		JPanel panel = new JPanel(new BorderLayout(5, 5));
		panel.setBorder(new javax.swing.border.EmptyBorder(5, 5, 5, 5));
		panel.add(srcFrame, BorderLayout.WEST);
		panel.add(dstFrame, BorderLayout.EAST);
		//panel.add(new JLabel("A.Greensted - http://www.labbookpages.co.uk", JLabel.CENTER), BorderLayout.SOUTH);

		JFrame frame = new JFrame("Blob Detection Demo");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.getContentPane().add(panel);
		frame.pack();
		frame.setVisible(true);*/
		return blobList;
	}
	
	

public static void main(String[] args)
	{
		System.out.println("Blob Finder Demo - A.Greensted - http://www.labbookpages.co.uk");
		BufferedImage src = null;
		
	
		try
		{
			File imgFile = new File("/avion_1.png");
			src = javax.imageio.ImageIO.read(imgFile);
		}
		catch (IOException ioE)
		{
			System.err.println(ioE);
			System.exit(1);
		}
	/*	src=utilidades.toBufferedImage(src); 	
		
		utilidades.salvarImagen(src,"/zz.png","png");
		*/
		
		src=utilidades.binariza(src);
		BlobDemo blob =  new BlobDemo();
        
		
		List<Blob> blobList = blob.BlobDemo(src);
		
	//	String s  = "/Volumes/programacion/avion.jpg";
	
	}
}
